"""
-*- coding:utf-8 -*-
最终版web自动化
Author: Free
DataTime: 2020/1/10 16:26
TODO 开始运行的执行通道
在此运行所有用例

"""
import unittest
import time
import HTMLTestRunnerCN
from tomorrow3 import threads
import os
from WebSite.tools.emalTool import EmailTool

# report_dir = './TestReport'
# test_dir = './TestCase'

# print('开始执行用例')
# discover = unittest.defaultTestLoader.discover(test_dir, pattern='Tester*.py')  # TODO 填写需要测试的类名
# suite = unittest.TestSuite()
# now = time.strftime('%Y-%m-%d %H_%M_%S')
# report_name = report_dir + '/' + now + '测试报告.html'
#
# print('生成报告中。。。')
# suite.addTest(discover)
# f = open(report_name, 'wb')  # wb 二进制文件的写操作
# runner = HTMLTestRunnerCN.HTMLTestRunner(stream=f, title='币君测试报告', description='PC端')
# # f.close()
# runner.run(suite)
#
# 使用多线程方式进行执行用例
# 获取路径
cur_path = os.path.dirname(os.path.realpath(__file__))
case_path = os.path.join(cur_path, "./TestCase")
report_path = os.path.join(cur_path, "./TestReport")

now = time.strftime('%Y-%m-%d %H_%M_%S')
report_name = report_path + '/' + now + '测试报告'


def add_case(case_path=case_path, rule="Tester*.py"):
    """
    加载所有的测试用例
    :param case_path: 用例的路径
    :param rule: 执行用例的规则
    :return: 所有用例集合
    """
    discover = unittest.defaultTestLoader.discover(case_path,
                                                   pattern=rule,
                                                   top_level_dir=None)
    return discover


# TODO 需要几个线程进行执行
@threads(3)
def run_case(all_case, report_path=report_path, nth=0):
    """
    执行所有的用例, 并把结果写入测试报告
    :param all_case: 所有的用例，调用add_case函数返回值
    :param report_path: 测试报告路径
    :param nth: 记录测试报告次数
    :return: 无
    """
    t = EmailTool()
    report_abspath = os.path.join(report_path, report_name + "%s.html" % nth)
    f = open(report_abspath, "wb")
    runner = HTMLTestRunnerCN.HTMLTestRunner(stream=f, title='币君测试报告', description='PC端')
    runner.run(all_case)
    t.mail_html("测试报告", f)
    f.close()


if __name__ == "__main__":
    # 用例集合
    cases = add_case()
    # 之前是批量执行，这里改成for循环执行
    for i, j in zip(cases, range(len(list(cases)))):
        run_case(i, nth=j)  # 执行用例，生成报告

